// 导入封装的 接口 API 函数
import {
  request,
} from '../../utils/requestUtils';
import { userBehavior } from '../../behaviors/userBehavior'

import {
  debounce
} from 'miniprogram-licia'
Page({
  behaviors: [userBehavior],
  // 初始化数据
  data: {
    carNum: '',
    categoryList: [], // 商品分类列表数据
    activeIndex: 0, // 被激活那一项的索引，默认是 0
    params: {
      categoryType: '1'
    }
  },

  // 实现一级分类的切换效果
  updateActive(event) {
    // console.log(event.currentTarget.dataset)
    const { index } = event.currentTarget.dataset
    this.setData({
      activeIndex: index
    })
  },

  // 获取商品分类的数据
  async getCategoryData() {
    const result = await request({
      url: `/merchant/customer/category/query`,
      method: "POST",
      data: {
        categoryType: this.data.params.categoryType,
        params: {
          keywords: ''
        }
      }
    })
    if (result.data.code === 200) {
      this.setData({
        categoryList: result.data.data
      })
    }
  },

  // 监听页面的加载
  onLoad(options) {
   
  },

  // 监听是否更改了购买数量
  onCarNumChange: debounce(async function (event) {
    console.log('event', event)
    const {detail} = event
    const {id, index} = event.target.dataset
    const result = await request({
      url: `/bus/customer/cart`,
      method: "POST",
      data: {
        productId:id,
        carNum: detail,
        checked:2
      }
    })
    if(result.data.code == 200){
      this.getCartNum()
    }
  }, 500),

  async getCartNum() {
    const result = await request({
      url: `/bus/customer/cart/cartNum`,
      method: "GET"
    })
    if (result.data.code == 200) {
      this.setCarNum(result.data.data)
    }
  },
  // 跳转商品详情
  toProductDetails(event){
    console.log('event', event)
    if (event.target.id === 'child') return
    const {id, index} = event.currentTarget.dataset
    console.log('id', id)
    wx.navigateTo({
      url: '/pages/customer_product_details/index?id='+id,
    })
  },
  initType(categoryType){
    let component = this.selectComponent('#productType')
    if (component) {
      component.initInfo(categoryType);
    }
  },
  // 选中分类
  productTypeConfirm(e){
    console.log('e',e)
    this.setData({
      'params.categoryType':e.detail
    })
    this.getCategoryData()
     wx.setStorageSync('categoryType', e.detail);

  },
  onShow(){
    this.getTabBar().setData({
      active: 1
    })
    let categoryType = wx.getStorageSync('categoryType');
    if(categoryType){
      this.setData({
        'params.categoryType': categoryType
      })
    }
    this.initType(this.data.params.categoryType)
    this.getCategoryData()
  }
})
